
var toDictIndexUrl = rootPath + "s/sys/dict/index.cgi";
var toEditDictPageUrl = rootPath + "s/sys/dict/edit.cgi";//增加或修改页面

var pageListUrl = rootPath + "s/sys/dict/pagelist";//分页显示
var saveDictUrl = rootPath + "s/sys/dict/save";//保存
var removeDictUrl = rootPath + "s/sys/dict/del";//删除
var detailDictUrl = rootPath + "s/sys/dict/detail";//获取详情

function queryList(){
	var results;
    $("#datagrid").datagrid({
//        url : pageListUrl,
        pagination:true,//分页控件
        width : 'auto',// 面板宽度，自动列宽 
        height : 'auto',// 面板高度，自动列高 
        nowrap : false,// :当true时，显示数据在同一行上。默认true。
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNo :0,
        pageSize :10,
        queryParams : getQueryParam(),
        loadFilter : function (data) {
            if(data.opStatus == "0"){
            	$("#pageNo").val(data.data.pageNo);
            	$("#pageSize").val(data.data.pageSize);
            	results = data.data.results;
            	var rs ={
            		"rows":	data.data.results,
            		"total":data.data.totalRecord
            	};
                return rs;
                
            }
        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'dictCode',
            title : '数据字典编码',
            width : '20%',
            align : 'center'
        }, {
            field : 'dictName',
            title : '名称',
            width : '20%',
            align : 'center'
        }, {
            field : 'description',
            title : '描述',
            width : '30%',
            align : 'center'
        },{
            field : 'dictId',
            title : '操作',
            width :'25%',
            align : 'center',
            formatter:function(dictId){
                var str = '<button class="btn btn-default btn-xs" type="button" onclick="toEditDictPage(\''+dictId+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改</button>';
                str += ' <button class="btn btn-default btn-xs" type="button" onclick="toDictItemPage(\''+dictId+'\')"> 查看元素</button>';
                return str;
            }
        }] ],
        onDblClickRow : function(index,row){
        }
    });
}

//获取表单参数
function getQueryParam() {
	var pageNo;
	var pageNoStr = $("#pageNo").val();
	if(pageNoStr && pageNoStr != ""){
		pageNo = parseInt(pageNoStr);
	}
	var pageSize;
	var pageSizeStr = $("#pageSize").val();
	if(pageSizeStr && pageSizeStr != ""){
		pageSizeStr = parseInt(pageSizeStr);
	}
	
	var param = {
    		pageNo : pageNo,
    		pageSize : pageSize,
            "sysDict.dictCode" : $("#code_search").val(),
            "sysDict.dictName" : $("#name_search").val(),
    };
    return param;
	
}

//刷新
function refreshGrid(){
	 $("#datagrid").datagrid("reload",getQueryParam());
}

//批量删除
function removeDict(dictIds) {
    var idsStr = dictIds.join(",");
    $.ajax({
        url : removeDictUrl,
        type : 'post',
        data :{ids :idsStr},
        success : function (res) {
            if(res.opStatus == "0"){
                showTip(res.msgDesc,1000,function () {
                	refreshGrid();
                });
            }else {
                showMsg(res.msgDesc);
            }
        }
    })
};

//保存
function saveDict() {
	var valiMsg = validate();//验证表单信息
    if(valiMsg != ""){
        showMsg(valiMsg);
        return;
    }
	var param = {
		
		"sysDict.dictId" : $("#dictId").val(),
		"sysDict.dictCode" : $("#code").val(),
		"sysDict.dictName" : $("#name").val(),
		"sysDict.description" : $("#description").val(),
		
		
	}
	$.ajax({
        url : saveDictUrl,
        type : 'post',
        data : param,
        success :function (res) {
        	if(res.opStatus == "0"){
        	 showTip(res.msgDesc,1000,function () {
                 $("#editModal").modal("hide");

                 refreshGrid();
             });
        	}else {
              showMsg(res.msgDesc);
        	}
        }
    });
}

//转到编辑页面（修改或增加）
function toEditDictPage(dictId){
	if(dictId && dictId != ""){
		//修改
		$("#edit-modal").load(toEditDictPageUrl + "?dictId=" + dictId,{_: Math.random()},function () {
			 $.ajax({
		            url : detailDictUrl,
		            type : 'post',
		            data :{'id' : dictId},
		            success :function (res) {
		            	debugger;
		               if( res.opStatus == "0"){
		            	   $("#dictId").val(res.data.dictId);
		            	   $("#code").val(res.data.dictCode);
		                   $("#name").val(res.data.dictName);
		                   $("#description").val(res.data.description);
		                   $("#code").attr("readonly","readonly");
		               }else {
		            	   showMsg(res.msgDesc);
		               }
		               $('#editModalLabel').html("修改");
		               $('#editModal').modal('show');
		               
	                }
		        });
		    });
	}else {//添加
		$("#edit-modal").load(toEditDictPageUrl,{_: Math.random()},function () {
			 $('#editModal').modal('show');
		});
	}
}

function toDictItemPage(dictId){
	Index.loadPage("s/sys/dict/item/index.cgi?dictId=" + dictId);
}


//验证表单信息
function validate(){
	var msg = "";
	//必填项的自定义属性 require 为 true,获取这些 input ,如果所填内容为空，则显示提示信息（data-message属性）
	var inputs = $("#dictEdit input[require='true']");
	var err = checkEmpty(inputs);
	debugger;
	$(err).each(function(){
		msg += $(this).attr("data-message")+"</br>";
	});
	
	return msg;
}

$(document).ready(function () {
	queryList();// 加载分页数据
	
	$("#search_button").on("click",function () {
		refreshGrid();
    });
	
	$("#remove_button").on("click",function () {
    	var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length > 0){
            showConfirm("是否确认删除？",function () {
                var dictIds = [];
                for(var i in rows ){
                	dictIds.push(rows[i].dictId);
                }
                removeDict(dictIds);
            });
        }else {
            showMsg("请选择要删除的数据字典！");
        }
		
	});
	
	$("#add_button").on("click",function(){
		toEditDictPage("");
	});
	
	var rows = $("#datagrid").datagrid("getPager");
	 $("#datagrid").datagrid({
		url : pageListUrl,
        onBeforeLoad:function(param){
            param.pageSize = param.rows;
            param.pageNo = param.page;
            param.rows = null;
            param.page = null;
        }
    }); 
	
});

